package com.xiaomage.view.draw10

import android.content.Context
import android.graphics.*
import android.view.View

/**
 * Created by Administrator on 2018/1/7.
 */
class MyView4(context: Context): View(context) {
    private val paint1=getPaint()
    private lateinit var dstBitmap:Bitmap
    private lateinit var srcBitmap:Bitmap
    init {
        dstBitmap=makeDstBitmap()
        srcBitmap=makeSrcBitmap()
        //禁用硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE,null)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //新建图层
        val layerId=canvas.saveLayer(0f,0f,500f,500f,
                paint1, Canvas.ALL_SAVE_FLAG)

        //核心代码
        canvas.drawBitmap(dstBitmap,0f,0f,paint1)
        paint1.xfermode= PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(srcBitmap,250f,250f,paint1)
        paint1.xfermode=null

        //还原图层
        canvas.restoreToCount(layerId)

    }
    private fun makeDstBitmap():Bitmap{
        val bitmap=Bitmap.createBitmap(500,500,Bitmap.Config.ARGB_8888)
        val canvas=Canvas(bitmap)
        val paint=Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color= 0xffffcc44.toInt()
        canvas.drawOval(RectF(0f,0f,500f,500f),paint)
        return bitmap
    }
    private fun makeSrcBitmap():Bitmap{
        val bitmap=Bitmap.createBitmap(500,500,Bitmap.Config.ARGB_8888)
        val canvas=Canvas(bitmap)
        val paint=Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color=0xFF66AAFF.toInt()
        canvas.drawRect(0f,0f,500f,500f,paint)
        return bitmap
    }
    private fun getPaint(): Paint {
        val paint= Paint()
        paint.isAntiAlias=true
        paint.style= Paint.Style.STROKE
        paint.strokeWidth=5f
        paint.color= Color.RED
        return paint
    }
}